/**
 * @author
 * @createtime
 * @class DesignChangeForm
 * @extends Ext.Window
 * @description DesignChange表单
 */
DesignChangeForm = Ext.extend(Ext.Window, {
			// 内嵌FormPanel
			formPanel : null,
			// 构造函数
			constructor : function(_cfg) {
				Ext.applyIf(this, _cfg);
				// 必须先初始化组件
				this.initUIComponents();
				DesignChangeForm.superclass.constructor.call(this, {
							id : 'DesignChangeFormWin',
							layout : 'fit',
							items : this.formPanel,
							modal : true,
							width : 800,
							height : 350,
							maximizable : true,
							title : '[设计变更申请]详细信息',
							buttonAlign : 'center',
							buttons : this.buttons
						});
			},// end of the constructor
			// 初始化组件
			initUIComponents : function() {
				var thizId = this.id;
				this.formPanel = new Ext.FormPanel({
							layout : 'form',
							trackResetOnLoad : true,
							bodyStyle : 'padding:10px 10px 10px 10px',
							border : false,
							url : __ctxPath + '/project/saveDesignChange.do',
							id : 'DesignChangeForm',
							defaults : {
								anchor : '98%,98%'
							},
							defaultType : 'textfield',
							items : [{
										name : 'designChange.id',
										id : 'id',
										xtype : 'hidden',
										value : this.id == null ? '' : this.id
									},{
										xtype : 'container',
										layout : 'column',
										height : 25,
										defaults : {
											xtype : 'label',
											style : {
												margin : '0px 0px 3px 0px'
											}
										},
										items : [{
													text : '项目名称：',
													width : 60
												}, {
													xtype : 'textfield',
													name : 'designChange.project.proName',
													id : 'designChange.project.proName',
													columnWidth : .4,
													allowBlank : false,
													emptyText : '请选择项目',
													listeners : {
														'focus' : function() {
															ProjectSelector.getView(function(proId, proName, proNo,managerId,managerName) {
																Ext.getCmp("designChange.project.id").setValue(proId);
																Ext.getCmp("designChange.project.proName").setValue(proName);
															}, true).show();
														}
													}
												}, {
													xtype : "hidden",
													name : "designChange.project.id",
													id : "designChange.project.id"
												}, {
													text : '登记人：',
													style : 'margin-left:10px;',
													width : 60
												}, {
													xtype : 'textfield',
													name : 'designChange.applyUser.fullname',
													id : 'designChange.applyUser.fullname',
													readOnly:true,
													columnWidth : .3,
													value:__currentUser
												},{
													xtype:'hidden',
													name:'designChange.applyUser.userId',
													id:'designChange.applyUser.userId',
													value:__currentUserId
												}, {
													text : '填写日期：',
													style : 'margin-left:10px;',
													width : 60
												}, {
													xtype : 'datefield',
													name : 'designChange.formDate',
													id : 'formDate',
													format:'Y-m-d',
													value:new Date(),
													columnWidth : .3
												}
												]
									}, {
										xtype : 'container',
										layout : 'column',
										height : 25,
										defaults : {
											xtype : 'label',
											style : {
												margin : '0px 0px 3px 0px'
											}
										},
										items : [{
													text : '详情：'
												}, {
													style : 'color:red',
													id : 'designChangeErrorLabel',
													text : '(*必填)'
												}]
									}, {
										xtype : 'container',
										style : 'padding-left:0px;margin-bottom:10px',
										layout : 'column',
										items : [{
													name : 'resultGridData',
													xtype : 'hidden',
													id : 'designChange.resultGridData'
												}, {
													name : 'dataList',
													xtype : 'hidden',
													id : 'designChange.dataList'
												}, {
													xtype : 'grid',
													id : 'designChange.resultGridDataGrid',
													height : 220,
													width : '98%',
													stripeRows : true,
													trackMouseOver : true,
													clicksToEdit : 1,
													plugins : [new Ext.ux.grid.RowEditor({
																saveText : '保存',
																cancelText : '取消',
																errorText : '请输入完整信息',
																errorSummary : false
															})],
													store : new Ext.data.JsonStore({
														url : __ctxPath + '/project/listDesignChangeInfo.do',
														root : 'result',
														totalProperty : 'totalCounts',
														remoteSort : true,
														fields : ['id', 'fileNo', 'eventDesc','remark', 'fileAttachs'],
														listeners : {
															'update' : function(value) {
																var r = this.getRange();
																var resultArray = [];
																var jsonArr = [];
																var sum = 0;
																var rlen = r.length;
																for (var i = 0; i < rlen; i++) {
																	resultArray.push([]);
																	if (r[i].fields) {
																		var fields = r[i].fields;
																		var flen = fields.length;
																		var obj = {}
																		var isAdd = false;
																		for (var z = 0; z < flen; z++) {
																			var fieldValue = r[i].get(fields.keys[z]);
																			if (Ext.isEmpty(fieldValue) || fieldValue == '请双击选择' || fieldValue == '请双击填写') {
																				continue;
																			}
																			isAdd = true;
																			if (fields.keys[z] == 'id') {
																				resultArray[i].push('ID:' + fieldValue);
																				if (fieldValue != '') {
																					obj.id = fieldValue;
																				}
																			} else if (fields.keys[z] == 'fileNo') {
																				resultArray[i].push('文件编号:' + fieldValue);
																				obj.fileNo = fieldValue;
																			} else if (fields.keys[z] == 'eventDesc') {
																				resultArray[i].push('事件描述:' + fieldValue);
																				obj.eventDesc = fieldValue;
																			} else if (fields.keys[z] == 'remark') {
																				resultArray[i].push('备注:' + fieldValue);
																				obj.remark = fieldValue;
																			} else if (fields.keys[z] == 'fileIds') {
																				resultArray[i].push('附件ID:' + fieldValue);
																				obj.fileIds = fieldValue;
																			} else if (fields.keys[z] == 'fileContents') {
																				resultArray[i].push('附件:' + fieldValue+ ';');
																			}
																		}
																		if(isAdd){
																		  jsonArr.push(obj);
																		}
																	}
																}
																//删除空元素
																for (var i = 0; i < resultArray.length; i++) {
																	if (resultArray[i].length == 0) {
																		resultArray.splice(i, 1);
																		i--;
																	}
																}
																Ext.getCmp('designChange.dataList').setValue(Ext.util.JSON.encode(jsonArr));
																Ext.getCmp('designChange.resultGridData').setValue(resultArray);
															}
														}
													}),
													cm : new Ext.grid.ColumnModel({
														columns : [new Ext.grid.RowNumberer(), {
																	dataIndex : 'id',
																	width : 50,
																	hidden : true
																}, {
																	header : '文件编号',
																	dataIndex : 'fileNo',
																	editor : new Ext.grid.GridEditor(new Ext.form.TextField({
																		allowBlank : false,
																		maxLength : 64,
																		listeners : {
																			focus : function(field) {
																				if (field.getValue() == '请双击填写') {
																					field.setValue('');
																				}
																			}
																		}
																	}))
																}, {
																	header : '事件描述',
																	dataIndex : 'eventDesc',
																	width:150,
																	editor : new Ext.grid.GridEditor(new Ext.form.TextField({
																		allowBlank : false,
																		maxLength : 64,
																		listeners : {
																			focus : function(field) {
																				if (field.getValue() == '请双击填写') {
																					field.setValue('');
																				}
																			}
																		}
																	}))
																}, {
																	header : '备注',
																	dataIndex : 'remark',
																	width:200,
																	editor : new Ext.grid.GridEditor(new Ext.form.TextField({
																		allowBlank : true
																	}))
																}, {
																	header : '',
																	dataIndex : 'fileIds',
																	editor : new Ext.grid.GridEditor(new Ext.form.Hidden({
																		id : 'designChangeInfo.fileIds'
																	})),
																	hidden:true
																}, {
																	header : '附件',
																	dataIndex : 'fileContents',
																	width : 260,
																	editor : new Ext.grid.GridEditor(new Ext.form.TextField({
																		id : 'designChangeInfo.fileContents',
																		readOnly:true,
																		emptyText:'请上传附件',
																		listeners:{
																			focus:function(field){
																				var dialog = App.createUploadDialog({
																						file_cat : 'flow/designChange',
																						callback : function(data) {
																							if(!Ext.isEmpty(data)){
																								var attachFiles = Ext.getCmp("designChangeInfo.fileContents");
																								var fileIds = Ext.getCmp('designChangeInfo.fileIds');
																								fileIds.setValue('');
																								var str= "";
																								for (var i = 0; i < data.length; i++) {
																									if (fileIds.getValue() != '') {
																										fileIds.setValue(fileIds.getValue()+ '|');
																									}
																									fileIds.setValue(fileIds.getValue()+data[i].fileId);
																									str+='<span><a href="#" onclick="FileAttachDetail.show('+data[i].fileId+')">'+data[i].filename.replace(/\s+/g,"")+'</a>  |  </span>';
																								}
																								Ext.getCmp('designChangeInfo.fileContents').setValue(str);
																								Ext.getCmp('designChangeInfo.fileIds').setValue(fileIds.getValue());
																							}
																						},
																						permitted_max_size :1024*1024*20
																					});
																				dialog.show(this);
																			}
																		}
																	})),
																	renderer:function(value,meta,record){
																		var fileAttachs = record.data.fileAttachs;
																		var str = "";
																		Ext.each(fileAttachs,function(item,i){
																			str+='<span><a href="#" onclick="FileAttachDetail.show('+item.fileId+')">'+item.fileName.replace(/\s+/g,"")+'</a>  |  </span>';
																		});
																		return str;
																	}
																}
																],
														defaults : {
															sortable : false,
															menuDisabled : false,
															width : 100
														}
													}),
													tbar : new Ext.Toolbar({
														height : 30,
														items : [{
																	iconCls : 'btn-add',
																	text : '添加',
																	xtype : 'button',
																	handler : function() {
																		var DataRecord = Ext.data.Record.create([{
																					name : 'id'
																				}, {
																					name : 'fileNo'
																				}, {
																					name : 'eventDesc'
																				}, {
																					name : 'remark'
																				}, {
																					name : 'fileIds'
																				}, {
																					name : 'fileContents'
																				}]);
																		var store = Ext.getCmp('designChange.resultGridDataGrid').store;
																		var grid = Ext.getCmp('designChange.resultGridDataGrid');
					
																		var n1 = '请双击填写';
																		var n2 = '';
																		
																		var newRowData = {
																			fileNo : n1,
																			eventDesc : n1,
																			remark:n2,
																			fileIds:n2,
																			fileContents:n2
																		};
																		var newRecord = new DataRecord(newRowData);
																		store.add([newRecord]);
					
																		grid.getSelectionModel().on('selectionchange', function(sm) {
																			Ext.getCmp('designChange.removeBtn').setDisabled(sm.getCount() < 1);
																		});
																	}
																}, {
																	iconCls : 'btn-del',
																	text : '删除',
																	id : 'designChange.removeBtn',
																	xtype : 'button',
																	handler : function() {
																		var store = Ext.getCmp('designChange.resultGridDataGrid').store;
																		var grid = Ext.getCmp('designChange.resultGridDataGrid');
																		var s = grid.getSelectionModel().getSelections();
																		for (var i = 0, r; r = s[i]; i++) {
																			store.remove(r);
																		}
																		store.fireEvent("update");//更新事件
																	}
																}]
													})
												}]
									}, {
										xtype : 'textfield',
										hidden : true,
										validator : function() {
											var resultGridData = Ext.getCmp('designChange.resultGridData').getValue();
											var errorLabel = Ext.getCmp("designChangeErrorLabel");
											if (Ext.isEmpty(thizId)) {
												if (Ext.isEmpty(resultGridData)) {//为空显示提示
													errorLabel.setText('请填写详情');
													return false;
												}
											}
											return true
										}
									}

							]
						});
				// 加载表单对应的数据
				this.initData();
				// 初始化功能按钮
				this.buttons = [
//					{
//							text : '保存',
//							iconCls : 'btn-save',
//							handler : this.save.createCallback(this.formPanel,
//									this)
//						}, {
//							text : '重置',
//							iconCls : 'btn-reset',
//							handler : this.reset.createCallback(this.formPanel)
//						},
						{
							text : '关闭',
							iconCls : 'btn-cancel',
							handler : this.cancel.createCallback(this)
						}];
			},// end of the initcomponents
			/**
			 * 初始化数据
			 * 
			 * @param {}
			 *            formPanel
			 */
			initData : function() {
				// 加载表单对应的数据
				if (this.id != null && this.id != 'undefined') {
					Ext.getCmp('designChange.resultGridDataGrid').getStore().load({params:{
							'Q_designChange.id_L_EQ':this.id,
							start:0,
							limit:9999
					}});
					this.formPanel.getForm().load({
						deferredRender : false,
						url : __ctxPath + '/project/getDesignChange.do?id='
								+ this.id,
						waitMsg : '正在载入数据...',
						success : function(form, action) {
							var jsonData = Ext.util.JSON
									.decode(action.response.responseText);
							var res = jsonData.data;
							if (!Ext.isEmpty(res.project)) {
								Ext.getCmp("designChange.project.proName").setValue(res.project.proName);
								Ext.getCmp("designChange.project.proName").originalValue = res.project.proName;
								Ext.getCmp("designChange.project.id").setValue(res.project.id);
								Ext.getCmp("designChange.project.id").originalValue = res.project.id;
							}
							if (!Ext.isEmpty(res.applyUser)) {
								Ext.getCmp("designChange.applyUser.fullname").setValue(res.applyUser.fullname);
								Ext.getCmp("designChange.applyUser.fullname").originalValue = res.applyUser.fullname;
								Ext.getCmp("designChange.applyUser.userId").setValue(res.applyUser.userId);
								Ext.getCmp("designChange.applyUser.userId").originalValue = res.applyUser.userId;
							}
							// Ext.getCmp("").originalValue=
						},
						failure : function(form, action) {
						}
					});
				}
			},
			/**
			 * 重置
			 * 
			 * @param {}
			 *            formPanel
			 */
			reset : function(formPanel) {
				formPanel.getForm().reset();
			},
			/**
			 * 取消
			 * 
			 * @param {}
			 *            window
			 */
			cancel : function(window) {
				window.close();
			},
			/**
			 * 保存记录
			 */
			save : function(formPanel, window) {
				if (formPanel.getForm().isValid()) {
					formPanel.getForm().submit({
								method : 'POST',
								waitMsg : '正在提交数据...',
								success : function(fp, action) {
									Ext.ux.Toast.msg('操作信息', '成功保存信息！');
									var gridPanel = Ext
											.getCmp('DesignChangeGrid');
									if (gridPanel != null) {
										gridPanel.getStore().reload();
									}
									window.close();
								},
								failure : function(fp, action) {
									Ext.MessageBox.show({
												title : '操作信息',
												msg : '信息保存出错，请联系管理员！',
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.ERROR
											});
									// window.close();
								}
							});
				}
			}// end of save

		});